﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MVCExtension.FrameWork;
using System.Data;

namespace MVCExtension.Authorize
{
    /// <summary>
    /// 权限过滤系统
    /// </summary>
    [ExceptionLog]
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthorizeFilterAttribute : ActionFilterAttribute
    {

         public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            var path = filterContext.HttpContext.Request.Path.ToLower();
            if (path == "/" || path == "/Account/LogOn".ToLower() || path == "/Main/UserLogin".ToLower())
                return;//忽略对Login登录页的权限判定

            //if (!filterContext.HttpContext.User.Identity.IsAuthenticated)//如果没有登录
            //{
            //    filterContext.Result = new HttpUnauthorizedResult();//直接URL输入的页面地址跳转到登陆页
            //}



            //object[] attrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ViewPageAttribute), true);
            //var isViewPage = attrs.Length == 1;//当前Action请求是否为具体的功能页

            //if (!isViewPage)
            //{

            //    if (this.AuthorizeCore(filterContext) == false)//根据验证判断进行处理
            //    {

            //        Logger.Debug("验证失败，没有权限！");
            //        filterContext.Result = new ContentResult { Content = @"alert('抱歉,你不具有当前操作的权限！')" };//功能权限弹出提示框

            //    }
            //}
        }
        //权限判断业务逻辑
        protected virtual bool AuthorizeCore(ActionExecutingContext filterContext)
        {

            
            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            var actionName = filterContext.RouteData.Values["action"].ToString();


            if (!LogOnAction.CheckUserPower(controllerName, actionName))
            {
                return false;
            }

            return true;
        }
    }

}
